package sunwin.yoms.service.publicty;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jodd.datetime.JDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sunwin.yoms.comm.*;
import sunwin.yoms.dao.VideoDao;
import sunwin.yoms.domain.publicty.VideoDomain;
import sunwin.yoms.service.comm.YomsDefaultData;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by watson on 2015/7/28.
 */
@Service
public class VideoService {
    @Autowired
    private VideoDao videoDao;

    /**
     * 查询视频
     *
     * @param videoDomain
     * @return
     */
    public List<VideoDomain> getVideoDomain(VideoDomain videoDomain, YomsPage yomsPage, Date startTime, Date endTime) throws YomsException {
        com.github.pagehelper.Page total = PageHelper.startPage(yomsPage.getPageIndex(), yomsPage.getPageSize(), true);
        List<VideoDomain> videoDomains;
        videoDomains = videoDao.getDomainCollectionExtend(videoDomain, startTime, endTime);
        yomsPage.setPageCount(total.getTotal() % yomsPage.getPageSize() == 0 ? total.getTotal() / yomsPage.getPageSize() : total.getTotal() / yomsPage.getPageSize() + 1);
        for (int i = 0; i < videoDomains.size(); i++) {
            try {
                VideoDomain fdomain = videoDomains.get(i);
                String base64 = null;
                File imgFile = new File(YomsDefaultData.WebRoot, "video/img/" + fdomain.getVideoFileName() + ".jpg");
                if (imgFile.exists()) {
                    base64 = Base64FileHelper.encodeBase64File(imgFile.getAbsolutePath());
                    base64 = "data:image/jpeg;base64," + base64;
                } else {
                    base64 = Base64FileHelper.encodeBase64File(new File(YomsDefaultData.WebRoot, "img/default/default-video.png").getAbsolutePath());
                    base64 = "data:image/png;base64," + base64;
                }
                fdomain.setVideoImage(base64);
            } catch (Exception e) {
                System.err.println("无法获取视频缩略图");
            }
        }
        if (videoDomains.size() == 0) {
            throw YomsException.getInstance("没有查找到视频", 1);
        }
        return videoDomains;
    }

    /**
     * 按照创建时间倒序排列
     *
     * @param yomsPage
     * @return
     */
    public List<VideoDomain> getVideoOrderByTime(YomsPage yomsPage) {
        return getVideoByPage(yomsPage, "video_create_time desc");
    }

    /**
     * 按照热度倒序排列
     *
     * @param yomsPage
     * @return
     */
    public List<VideoDomain> getVideoOrderByHot(YomsPage yomsPage) {
        return getVideoByPage(yomsPage, "video_heat desc");
    }

    /**
     * 更新视频热度
     * @param vid
     */
    public void updateHot(int vid) {
        VideoDomain videoDomain = videoDao.getDomainById(vid);
        if (videoDomain != null) {
            VideoDomain domain = new VideoDomain();
            domain.setVideoId(vid);
            domain.setVideoHeat(videoDomain.getVideoHeat() + 1);

            videoDao.updateDomain(domain);
        }
    }

    /**
     * 分页查找视频
     *
     * @param yomsPage
     * @return
     */
    private List<VideoDomain> getVideoByPage(YomsPage yomsPage, String oroder) {
        Page page = PageHelper.startPage(yomsPage.getPageIndex(), yomsPage.getPageSize(), true);
        PageHelper.orderBy(oroder);
        List<VideoDomain> domains = videoDao.getDomainCollection(null);

        for (VideoDomain videoDomain : domains) {
            String imgPath = "video/img/" + videoDomain.getVideoFileName() + ".jpg";
            videoDomain.setVideoImage(imgPath);
        }

        long total = page.getTotal();
        long pageCount = total % page.getPageSize() == 0 ? total / page.getPageSize() : total / page.getPageSize() + 1;

        yomsPage.setPageCount(pageCount);

        return domains;
    }

    /**
     * 根据视频视频获取视频名称
     *
     * @param id
     * @return
     */
    public String getVideoFileName(int id) throws YomsException {
        VideoDomain domain = this.getVideoById(id);
        if (domain == null || new File(YomsDefaultData.WebRoot, "video/" + domain.getVideoFileName()).exists() == false) {
            throw new YomsException("获取视频失败");
        }

        return domain.getVideoFileName();
    }

    /**
     * 根据ID查询视频
     *
     * @param videoId
     * @return
     */
    public VideoDomain getVideoById(int videoId) {
        return videoDao.getDomainById(videoId);
    }

    /**
     * 保存视频文件
     *
     * @param file
     * @return
     * @throws YomsException
     */
    public String SaveVideo(MultipartFile file) throws YomsException {
        String uuid;
        String fileName = null;

        if (!file.isEmpty()) {
            uuid = String.valueOf(UUID.randomUUID()).toUpperCase();
            fileName = uuid + "." + FileHelper.getExtensionName(file.getOriginalFilename());
            try {
                File videoFile = new File(YomsDefaultData.WebRoot, "video/" + fileName);
                file.transferTo(videoFile);

                buildVideoImg(fileName);
            } catch (IOException e) {
                throw new YomsException("保存视频文件失败");
            }
        }
        return fileName;
    }

    /**
     * 新增视频
     *
     * @param videoDomain
     * @throws YomsException
     */
    public void addVideoDomain(VideoDomain videoDomain) throws YomsException, InterruptedException {
        VideoDomain condition = new VideoDomain();
        condition.setVideoName(videoDomain.getVideoName());

        videoDomain.setVideoCreateTime(new JDateTime(System.currentTimeMillis()).convertToDate());
        videoDomain.setVideoVerifyStateId(YomsDefaultData.VerifyStateId);
        if (videoDao.addDomain(videoDomain) != 1) {
            throw new YomsException("上传视频失败");
        }
    }

    /**
     * 删除视频
     *
     * @throws YomsException
     */
    public void deleteVideoDomain(int id) throws YomsException {
        VideoDomain domain = new VideoDomain();
        domain.setVideoId(id);

        VideoDomain base = videoDao.getDomainById(id);
        if (base != null) {
            try {
                new File(YomsDefaultData.WebRoot, "video/" + base.getVideoFileName()).delete();
                new File(YomsDefaultData.WebRoot, "video/img/" + base.getVideoFileName() + ".jpg").delete();
            } catch (Exception e) {
                throw new YomsException("删除视频文件" + base.getVideoFileName() + "失败");
            }

            if (videoDao.deleteDomain(domain) != 1) {
                throw new YomsException("删除视频失败");
            }
        } else {
            throw new YomsException("无法找到该视频文件");
        }
    }

    /**
     * 生成视频缩略图
     *
     * @param fileName
     */
    private void buildVideoImg(String fileName) throws YomsException {
        String ffmpegPath = new File(YomsDefaultData.WebRoot, "ffmpeg/ffmpeg.exe").getAbsolutePath();
        String videoPath = new File(YomsDefaultData.WebRoot, "video/" + fileName).getAbsolutePath();
        String imgPath = new File(YomsDefaultData.WebRoot, "video/img/" + fileName + ".jpg").getAbsolutePath();

        try {
            VideoHelper.getVideoImage(ffmpegPath, videoPath, imgPath);
        } catch (YomsException e) {
            new File(videoPath).delete();
            e.printStackTrace();
        }
    }
}
